/**
 * @file dummy_malloc.c
 * @brief
 * Dummy mallocation is the simplest strategy:
 * - use `sbrk` to request mem
 * - Succeed, return starting address of mem block
 * - Failed, return NULL
 * 
 * @author WeixiongLin (wx_lin@outlook.com)
 * @version 1.0
 * @date 2022-09-19
 * 
 * @copyright Copyright (c) 2022  WeixiongLin
 * 
 * @par 修改日志:
 * <table>
 * <tr><th>Date       <th>Version <th>Author  <th>Description
 * <tr><td>2022-09-19 <td>1.0     <td>WeixiongLin     <td>好像不能直接使用 `malloc` 这个函数名, 否则 `malloc` 而不是 `main` 会被当作这个程序的入口, 但我不知道为什么
 * </table>
 * command: gcc dummy_malloc.c -o dummy_malloc.out && ./dummy_malloc.out
 */

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
// #include <stddef.h>

void *dummy_malloc(size_t size);

int main() {
    printf("main.begin()\n");
    // dummy_malloc(10);
    // dummy_malloc(100);
    dummy_malloc(1000);
    return 0;
}

/**
 * @brief implement dummy malloc
 * @param  size             size of memory to allocate
 * @return void* 
 */
void *dummy_malloc(size_t size) {
    void *p = sbrk(0);  // initial position of the break

    if (sbrk(size) == (void *) -1) return NULL;

    void *new_p = sbrk(0);

    printf("old pos of break: %p\n", p);
    printf("new pos of break: %p\n", new_p);
    printf("move of break: %lu\n", new_p - p);

    // 512 bits after [break] are still accessible, i wonder why
    // P.S. getconf PAGESIZE shows 4096, means page size is 4096 bytes
    for (int i = 0; ; i++) {
        printf("offset: %d\t", i);
        printf("value: %lu\n", *((size_t *) p + i));
    }

    return p;  // previous boundary returned
}
